﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Cache;
using Cache.Interface;

namespace SignalRService.Model
{
    public class OPMessage : ICacheObject
    {
        public PushContent content { get; set; }
        public string timetag { get; set; }
    }
    public class OPMessagePool
    {
        static OPMessagePool instant;
        public static OPMessagePool share
        {
            get
            {
                if(instant == null)
                {
                    instant = new OPMessagePool();
                }
                return instant;
            }
        }
        public List<OPMessage> pool
        {
            get
            {
                var list = CacheManager.instance.GetItemsFromPool<OPMessage>();
                if (list == null)
                    list = new List<OPMessage>();
                return list;
            }
        }

        public List<OPMessage> messagesByUser(string uid)
        {
            return this.pool.Where<OPMessage>(msg =>
            {
                return msg.content.to == uid;
            }).OrderByDescending(m=>m.timetag).ToList();
        }
        public void AddMessage(PushContent content)
        {
            OPMessage message = new OPMessage()
            {
                content = content,
                timetag = DateTime.Now.ToString("yyyyMMddHHmmss")
            };
            List<OPMessage> items = new List<OPMessage>() { 
                message
            };
            if(CacheManager.instance.doCacheItemsToPool<OPMessage>(items).isSuccessCached)
            {

            }
        }
        public void DeleteMessage(string messageId)
        {
            OPMessage message = this.pool.Find(m => m.content.messageid == messageId);
            if(message != null)
            {
                if(CacheManager.instance.DeleteItemFromPool<OPMessage>(message))
                {

                }
            }
        }
    }
}